<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Topic;

class TopicController extends Controller
{

    //展示标题
    public function show(Topic $topic)
    {
        //带文章数的标题
        $topic = Topic::withCount('postTopics')->find($topic->id);

        //标题下的文章列表
        $topicPosts = $topic->posts()->orderBy('created_at', 'desc')->take(10)->get();

        //属于我的文章,但是未投稿
        $myPosts = \App\Post::authBy(\Auth::id())->topicNotBy($topic->id)->get();
        
        return view('topic/show', compact('topic', 'topicPosts', 'myPosts'));
    }

    //提交主题
    public function submit(Topic $topic)
    {
        $this->validate(request(), [
            'post_ids' => 'required|array'
        ]);

        $topic_id = $topic->id;
        $post_ids = request('post_ids');
        foreach ($post_ids as $post_id) {
            \App\PostTopic::firstOrCreate(compact('post_id', 'topic_id'));
        }

        return back();
    }
}
